<template>
  <div style="width:100%;height:100%;overflow: hidden;" class="login-wrap">
    <!-- 手机号注册 -->
    <Row v-show='isTel' type="flex" align="middle" justify="center" style="width:100%;" class="register_form_bg">
      <Row type="flex" justify="space-between" style="width: 380px;">
       
        <Input
          v-model="phone"
          size="large"
          prefix="md-phone-portrait"
          placeholder="请输入手机号"
          maxlength="11"
          clearable
          class="f-mb10"
          @on-change='phoneChange'
        />
        <Alert v-if="!phoneStandard" type="error">{{ phoneError }}</Alert>
        <Button v-if='vcodeText' type="success" class='vcode-btn' style='width:100%;height:47px;border-color: transparent;' @click="onSubmit" long>点击按钮进行验证</Button>
        <div v-else class="usvc"></div>
        <Vcode
          :show="isShow"
          @success="onSuccess"
          @error='onError'
          @click="onClose(e)"
        />
        
        <div v-if='vCodeNumShow' class="verInput">
          <Input
            
            v-model="verificationCode"
            size="large"
            maxlength="6"
            placeholder="请输入验证码"
            clearable
            @on-change='verCodeChange'
            class="f-mb10 "
            style="width: 100%;"
          ></Input>
          <span v-if='disabled || timeNum > 0' class="append" style="cursor:not-allowed">{{codeText}}</span>
          <span v-else class="append" @click="startTimeFun">{{codeText}}</span>
        </div>

       <!--  <Button
         type="info"
         style="height:45px;line-height:35px!important;;background:#ffe0ca;border-color:#eb6100;font-size:20px;width:150px;padding:0;color: #eb6100;"
         @click="startTimeFun"
         :disabled="disabled || timeNum > 0">
         <span style="font-size:16px;">{{ codeText }}</span>
       </Button> -->

      </Row>
      <Row type="flex" class="formRow">
        <Tooltip
          content="已阅读并同意遵守《智慧能源综合服务平台服务条款》、《法律声明及隐私政策》协议"
          placement="top"
          theme="light"
          max-width="650"
        >
          <!-- <Checkbox label="agreement" @on-change='argeChange' v-model="agreement"></Checkbox> -->
        </Tooltip>
        <span @click="modal1=true"
          style="cursor:pointer; color:#0893fd;font-size:13px;">《智慧能源综合服务平台服务条款》|</span>
        <span @click="displayTermsService"
          style="cursor:pointer; color:#0893fd;font-size:13px;">《法律声明及隐私政策》</span>
      </Row>
      <Row
        type="flex"
        class="formRow"
        style="position: relative;margin-bottom:10px;">
        <Button :title="!registerShow?'请阅读服务条款与隐私协议':''" type="info" style="width:100%;height:45px;background:#0893fd;padding:0;z-index: 999;" @click="displayTermsServicetwo">
          <div style="line-height:45px!important;font-size:20px!important;">注册</div>
        </Button>
        <!--<div class="boxshadow"></div>-->
      </Row>
      <!-- <Row
        type="flex"
        class="formRow"
        v-else
        style="position: relative;margin-bottom:10px;"
        >
        <Button  type="info" style="width:100%;height:45px;background:#0f2554;padding:0;z-index: 999;border-color: transparent;cursor: not-allowed;" @click="displayTermsServicetwo">
          <div style="line-height:45px!important;font-size:20px!important;color:#1d4290;">注册</div>
        </Button>
      </Row> -->
      
    </Row>
    <!-- 设置密码 -->
    <Row v-show='isPassword' type="flex" align="middle" justify="center" style="width:100%;" class="register_form_bg">
      <Row type="flex" justify="space-between" style="width: 380px;">
        <p style='color:#0893fd;width: 100%;text-align: center;font-size:16px;' class="f-mb10">设置登录密码</p>
       
      </Row>
      <Row type="flex" justify="space-between" style="width: 380px;">
        <Input
          v-model="password"
          maxlength="16"
          size="large"
          prefix="md-lock"
          placeholder="请输入密码"
          type="password"
          autocomplete="new-password"
          clearable
          class="f-mb10"
        />
        <Alert v-if="!passwordStandard" type="error">密码必须是包含 字母、数字、特殊字符 的 8-16 位的字符串</Alert>

        <Input
          v-model="passwordConfirm"
          maxlength="16"
          size="large"
          :prefix="password == passwordConfirm ? 'md-lock' : 'md-alert'"
          placeholder="再次输入密码"
          type="password"
          autocomplete="new-password"
          clearable
          style="margin-bottom:15px;"
        />
        <Alert v-if="password != passwordConfirm" type="error">两次输入密码不一致</Alert>
       
      </Row>
      
      <Row
        
        type="flex"
        class="formRow"
        style="position: relative;margin-bottom:10px;">
        
        <Button v-if="!passwordStandard1||password !== passwordConfirm" type="info" style="width:100%;height:45px;background:#0f2554;padding:0;z-index: 999;border-color: transparent;cursor: not-allowed;">
          <div style="line-height:45px!important;font-size:20px!important;color:#1d4290;">注册</div>
        </Button>
        <Button v-else type="info" style="width:100%;height:45px;background:#0893fd;padding:0;z-index: 999;" @click="goUserInfo">
          <div style="line-height:45px!important;font-size:20px!important;">注册</div>
        </Button>
        <!--<div class="boxshadow"></div>-->
      </Row>
      
    </Row>
    <!-- 个人信息 -->
    <Row v-show='isUserInfo' type="flex" align="middle" justify="center" style="width:100%;" class="register_form_bg">
      <Row type="flex" justify="space-between" style="width: 380px;">
        <p style='color:#0893fd;width: 100%;text-align: center;font-size:16px;' class="f-mb10">完善个人信息</p>
       
      </Row>
      <Row type="flex" justify="space-between" style="width: 380px;">
        <Input
          v-model="name"
          size="large"
          maxlength="20"
          prefix="md-person"
          placeholder="请输入用户名"
          clearable
          class="f-mb10"
        />
        <Alert v-if="!nameStandard" type="error">{{ nameError }}</Alert>
       
      </Row>
      <!-- <Row type="flex" justify="space-between" style="width: 380px;">
        <p style='color:#0893fd;width: 100%;text-align: right;font-size:12px;cursor: pointer;' class="f-mb10">跳过,以后再说</p>
       
      </Row> -->
      <Row
        type="flex"
        class="formRow"
        style="position: relative;margin-bottom:10px;margin-top: 22px;">
        <Button type="info" style="width:100%;height:45px;background:#0893fd;padding-top:0;z-index: 999;" @click="register">
          <div style="line-height:45px!important;font-size:20px!important;">完成</div>
        </Button>
        <!--<div class="boxshadow"></div>-->
      </Row>
    </Row>
    <Row
        type="flex"
        class="formRow"
        style="position: relative;"
        align="middle"
        justify="center"
      >
        <div class="color-fff" style="width:200px;text-align:center;margin-top: 2%;">
          已有平台账号
          <span class="loginClick" @click="loginHandle">去登录</span>
        </div>
      </Row>
    <Modal class='argeCon' v-model="modal" width="1000" title="法律申明及隐私政策">
      <agreement />
      <div slot="footer" class="footer">
        <!-- <Checkbox class="agree" v-model="isAgree">法律申明及隐私政策</Checkbox> -->
        <!-- <Button type="primary" @click='modal=false'>同意并继续</Button>
        <span class="download">
          <Icon type="md-cloud-download" />立即下载
        </span> -->
      </div>
    </Modal>
    <Modal class='argeCon' v-model="modal1" width="1000" title="智慧能源综合服务平台服务条款">
      <userAgreement />
      <div slot="footer" class="footer">
        <!-- <Checkbox class="agree" v-model="isAgree">法律申明及隐私政策</Checkbox> -->
        <!-- <Button type="primary" @click='modal1=false'>同意并继续</Button>
        <span class="download">
          <Icon type="md-cloud-download" />立即下载
        </span> -->
      </div>
    </Modal>
    <Modal class='argeCon' v-model="modal2" width="1000" title="智慧能源综合服务平台服务条款" @on-cancel="cancel">
      <newAgreement @argebtnshow="argebtnshow"/>
      <!-- <userAgreement /> -->
      <div slot="footer" class="footer">
        <!-- <Checkbox class="agree" v-model="isAgree">法律申明及隐私政策</Checkbox> -->
        <Button type="primary" @click='newAgreeshow' v-if="argebtn">同意并继续</Button>
        <Button type="primary" v-else style="background:#f3f3f3;color:#666;padding:0;z-index: 999;border-color: transparent;cursor: not-allowed;">同意并继续</Button>
        <span class="download">
          <Icon type="md-cloud-download" />立即下载
        </span>
      </div>
    </Modal>
  </div>
</template>

<script>
import {
  getRandomCode,
  checkUser,
  register,
  validateCodeImgURL,
  checkCaptchaCode,
  getRandomCodeForSMS
} from "@/api/account.js";
import util from "@/libs/util.js";
import CryptoJS from "crypto-js";
import agreement from "./agreement";
import userAgreement from "./userAgreement.vue";
import newAgreement from "./newAgreement.vue";
import Vcode from "vue-puzzle-vcode";
export default {
  data() {
    return {
      //随机验证码，用于手机验证码接口
      randomCode: "",
      modal1:false,
      modal2:false,
      isShow:false,
      vcodeText:true,
      isPassword:false,
      isTel:true,
      isUserInfo:false,
      vCodeNumShow:false,
      registerShow:false,
      isPassing:true,
      nameError: null,
      emailError: null,
      phoneError: null,
      isAgree: false,
      modal: false,
      passwordUp: false,
      timeNum: 0,
      disabled: false,
      second: 60,
      name: "",
      email: "",
      phone: "",
      password: "",
      nameStandard: true,
      emailStandard: true,
      phoneStandard: true,
      passwordStandard: true,
      passwordStandard1: false,
      passwordConfirm: "",
      phoneReadonly: false,
      invitationCode: "",
      verificationCode: "",
      validateCode: "",
      agreement: false,
      validateCodeImgURL: "",
      timeStamp: "",
      aesKey: CryptoJS.enc.Utf8.parse("c9d2eea8faea11e996ed14ecd17545c4"),
      showFlag: true,
      argebtn:false,
      regisshow:false,
    };
  },
  watch: {
    password(val) {
      var numasc = 0;
      var charasc = 0;
      var otherasc = 0;

      if (val.length < 8 || val.length > 16) {
        this.passwordStandard = false;
        return;
      }

      for (var i = 0; i < val.length; i++) {
        var asciiNumber = val.substr(i, 1).charCodeAt();
        if (asciiNumber >= 48 && asciiNumber <= 57) {
          numasc += 1;
        }
        if (
          (asciiNumber >= 65 && asciiNumber <= 90) ||
          (asciiNumber >= 97 && asciiNumber <= 122)
        ) {
          charasc += 1;
        }
        if (
          (asciiNumber >= 33 && asciiNumber <= 47) ||
          (asciiNumber >= 58 && asciiNumber <= 64) ||
          (asciiNumber >= 91 && asciiNumber <= 96) ||
          (asciiNumber >= 123 && asciiNumber <= 126)
        ) {
          otherasc += 1;
        }
      }
      if (0 == numasc) {
        this.passwordStandard = false;
      } else if (0 == charasc) {
        this.passwordStandard = false;
      } else if (0 == otherasc) {
        this.passwordStandard = false;
      } else {
        this.passwordStandard = true;
      }
      this.passwordStandard1=this.passwordStandard
    },
  },
  computed: {
    codeText: function() {
      return this.timeNum > 0 ? this.timeNum + "s 后重获取" : "获取验证码";
    },
  },
  created() {
    this.setValidateCode();
  },
  methods: {
    cancel(){
      this.argebtn = false
    },
    argebtnshow(val){
      this.argebtn = val
    },
    goPassword(){
      // this.isPassword=true
      // this.isTel=false
      // this.isUserInfo=false
      let phone = CryptoJS.AES.encrypt(
              CryptoJS.enc.Utf8.parse(this.phone),
              this.aesKey,
              {
                mode: CryptoJS.mode.ECB,
              }
            ).toString();
      
      checkCaptchaCode({
        randomCode: this.randomCode,
        paramValue:this.verificationCode,
        aesPhone:phone
      }).then(res=>{
        if(res&&res.code==200){
          this.isPassword=true
          this.isTel=false
          this.isUserInfo=false
        }else{
          this.$Message.error(res.message);
        }
      })
    },
    goUserInfo(){
      this.isPassword=false
      this.isTel=false
      this.isUserInfo=true
    },
    verCodeChange(val){
      this.regisshow = this.phoneReadonly&&val&&this.verificationCode
    },
    phoneChange(val){
      if(!this.vcodeText){
        this.vcodeText=true
        this.vCodeNumShow=false
        this.timeNum=0
        this.verificationCode=""
        this.registerShow=false
      }
    },
    onSubmit(){
      if (!/^1[3456789]\d{9}$/.test(this.phone)) {
        this.$Message.error("手机号不可用");
        return;
      }
        this.isShow = true;
        let btn = document.querySelector(".vue-puzzle-vcode");
        // console.log(btn)
        let _this=this
        btn.addEventListener('click',function(e){
          
             //console.log(e,'++++++') 
          if(btn){
              if(e.target==btn){
                _this.isShow=false
              }
          }
          
        })
      },
      // 用户通过了验证
      onSuccess(msg){
        
        this.isShow = false; // 通过验证后，需要手动隐藏模态框
        let phone = CryptoJS.AES.encrypt(
          CryptoJS.enc.Utf8.parse(this.phone),
          this.aesKey,
          {
            mode: CryptoJS.mode.ECB,
          }
        ).toString();
        getRandomCodeForSMS({phone: phone}).then((res) => {
          if(res.code == 200){
            try{
              this.randomCode =  CryptoJS.AES.decrypt(res.result, this.aesKey, {mode: CryptoJS.mode.ECB}).toString(CryptoJS.enc.Utf8);
              this.vcodeText=false
              this.vCodeNumShow=true
            }catch(err){
              this.$Message.error("获取随机码出错！");
            }
          }else{
            this.$Message.error(res.message);
          }
        });
      },
      onError(){

      },
    loginHandle(){
      this.$emit('login')
    },
    appClick() {
      this.showFlag = !this.showFlag;
    },
    //显示服务条款
    displayTermsService() {
      this.modal = true;
    },
    //显示服务条款和法律
    displayTermsServicetwo() {
      if(this.regisshow){
        if(this.registerShow){//已经阅读了条款，进行下一步
          this.goPassword();
        }else{//没有阅读条款,弹出条款弹框
          this.modal2 = true;
        }
      }else{
        this.$Message.info("请点击获取验证码，并输入正确的验证码！")
      }
      // if(this.argebtn){
      //   this.registerShow=true
      // }else{
      //   this.registerShow=false
      // }
    },
    newAgreeshow(){
      this.modal2 = false;
      this.registerShow = true
    },
    checkUser(val, type, standard) {
      if (val == "" || val == null) {
        return;
      }
      if (type == 2) {
        val = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(val), this.aesKey, {
          mode: CryptoJS.mode.ECB,
        }).toString();
      }
      checkUser({
        paramVlue: val,
        type: type,
      }).then((res) => {
        if (res.code == 500) {
          this[standard] = false;
          switch (type) {
            case 1:
              this.nameError = res.message;
              break;
            case 2:
              this.phoneError = res.message;
              break;
            case 3:
              this.emailError = res.message;
              break;
          }
        } else {
          this[standard] = true;
        }
      });
    },
    openHome() {
      window.location = "https://zhny.hn.sgcc.com.cn/#/home";
    },
    // 获取验证码  更改验证码
    setValidateCode() {
      const timeStamp = new Date().getTime();
      this.timeStamp = timeStamp;
      this.validateCodeImgURL = validateCodeImgURL + "?time=" + timeStamp;
    },
    startTimeFun() {
      if (!/^1[3456789]\d{9}$/.test(this.phone) || !this.phoneStandard) {
        this.$Message.error("手机号不可用");
        return;
      }

      let phone = CryptoJS.AES.encrypt(
        CryptoJS.enc.Utf8.parse(this.phone),
        this.aesKey,
        {
          mode: CryptoJS.mode.ECB,
        }
      ).toString();

      const timeStamp = new Date().getTime();
      this.timeStamp = timeStamp;

      getRandomCode({ phone: phone, randomCode: this.randomCode}).then((res) => {
        if (res.code == 200) {
          this.$Message.success("验证码已发送");
          this.phoneReadonly = true;
          this.timeNum = this.second;
          this.timerFun();
        } else {
          this.phoneReadonly = false;
          this.$Message.error(res.message);
        }
      });
    },
    timerFun() {
      if (this.timeNum > 0) {
        this.timeNum--;
        setTimeout(this.timerFun, 1000);
      } else {
        this.disabled = false;
      }
    },
    register() {
      if (
        util.validate.isNull(
          [
            { title: "用户名", value: this.name },
            { title: "密码", value: this.password },
            { title: "重复密码", value: this.passwordConfirm },
            { title: "手机号", value: this.phone },
            { title: "验证码", value: this.verificationCode },
          ],
          this
        )
      ) {
        // if (!this.agreement) {
        //   this.$Message.error("未勾选用户协议");
        //   return;
        // }
        if (!this.nameStandard) {
          this.$Message.error("必须为有效的用户名格式");
          return;
        }
        // if (!this.emailStandard) {
        //   this.$Message.error("必须为有效的邮箱格式");
        //   return;
        // }
        if (!this.phoneStandard) {
          this.$Message.error("必须为有效的手机号格式");
          return;
        }
        if (!this.passwordStandard) {
          this.$Message.error("必须为有效的密码格式");
          return;
        }
        if (this.password != this.passwordConfirm) {
          this.$Message.error("重复密码不一致");
          return;
        }
        if (this.phone.length != 11) {
          this.$Message.error("必须为有效的电话号码");
          return;
        }

        if (!/^1[3456789]\d{9}$/.test(this.phone)) {
          this.$Message.error(this.phone);
          return;
        }

        let phone = CryptoJS.AES.encrypt(
          CryptoJS.enc.Utf8.parse(this.phone),
          this.aesKey,
          {
            mode: CryptoJS.mode.ECB,
          }
        ).toString();

        let password = CryptoJS.AES.encrypt(
          CryptoJS.enc.Utf8.parse(this.password),
          this.aesKey,
          {
            mode: CryptoJS.mode.ECB,
          }
        ).toString();

        let passwordConfirm = CryptoJS.AES.encrypt(
          CryptoJS.enc.Utf8.parse(this.passwordConfirm),
          this.aesKey,
          {
            mode: CryptoJS.mode.ECB,
          }
        ).toString();

        register({
          userNo: this.name,
          // email: this.email,
          password: password,
          repassword: passwordConfirm,
          phone: phone,
          code: this.verificationCode,
          invitationCode: this.invitationCode,
          randomCode: this.randomCode
        }).then((res) => {
          if (res.code == 200) {
            this.$Message.success("注册成功，欢迎登录综合能源系统");
            setTimeout(() => {
              // this.$router.push("login");
              this.loginHandle()
            }, 1000);
          } else {
            this.$Message.error(res.message);
          }
        });
      }
    },
  },
  components: {
    agreement,
    userAgreement,
    newAgreement,
    Vcode,
  },
};
</script>

<style lang="scss" scope>
.ivu-poptip{
  .ivu-poptip-rel{
    width:100%;
  }
}
.vcode-btn{
    width: 100%;
    height: 47px;
    border-radius: 4px;
    background-color: #7ecc4c;
    margin-top: 15px;
    margin-bottom: 25px;
    span{
      font-size: 20px;
    }
}
.usvc{
  width: 100%;
  height: 47px;
  margin-top: 15px;
  margin-bottom: 25px;
  background-image: url("~@/assets/img/login/suvs.png");
  background-size: 100% 100%;
}
.verInput{
  width: 100%;
  position: relative;
  .append{
    position: absolute;
    right: 13px;
    top:10px;
    color: #0893fd;
    cursor: pointer;
    font-size: 16px;
    
}

}

.argeCon{
  .ivu-modal-header{
    background: #f3f3f3;
    border-bottom: 1px solid transparent;
    .ivu-modal-header-inner{
      font-size: 16px;
      color:#333;
      font-weight: bold;
    }
  }
  .ivu-modal-body{
    // padding: 20px 10px 0px 30px
    padding: 0!important;
  }
  .ivu-modal-footer{
    border-top: 1px solid transparent;
    padding: 0 20px 12px;
    height: auto;
    button{
      width: 390px;
      height: 40px;
      
      span{
        font-size: 16px;
      }
    }
  }
  .footer{
    text-align: center;
    .download{
      margin-right:25px;
      color: #0893fd;
      float: right;
      .ivu-icon{
        font-size: 16px;
        margin-right: 6px;
        color: #0893fd
      }
    }
  }
}
.ivu-alert-error {
  background-color: rgba(240, 248, 255, 0);
  padding: 0;
  border: none;
  position: relative;
  top: -10px;
  margin-bottom: 0px;
  width: 100%;
  span {
    font-size: 12px;
    color: #ffb08f;
  }
}
.login_body {
  overflow: hidden;
  margin-top: -2px;
  height: 100%;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  -moz-background-size: 100% 100%;

  .validateCodeWrap {
    width: 100%;
    .validateCode {
      display: inline-block;
      vertical-align: middle;
      min-width: 100px;
      height: 45px;
      margin-left: 10px;

      img {
        cursor: pointer;
        height: 100%;
      }
    }
  }

  .boxshadow {
    box-shadow: 5px 5px 10px #6db0ff;
    border-radius: 90%;
    width: 98%;
    height: 40px;
    position: absolute;
    bottom: 0;
    left: 0;
  }

  h1 {
    color: white;
    font-size: 28px;
    font-weight: 300;
    margin: 50px 0;
  }

  h2 {
    color: black;
    font-size: 20px;
    font-weight: 300;
  }

  .login_form {
    border-radius: 7px;
    width: 1100px;

    .loginClick {
      color: #0893fd;
      cursor: pointer;
    }
    .loginClick:hover {
      text-decoration: underline;
    }

    .formRow {
      margin-top: 15px;
      width: 380px;

      img {
        margin: 0 10px;
        cursor: pointer;
      }

      .getPassword {
        color: #0893fd;
        span {
          cursor: pointer;
        }
        span:hover {
          text-decoration: underline;
        }
      }

      .ivu-btn > span {
        font-size: 15px !important;
      }

      .hr {
        height: 1px;
        width: 130px;
        background-color: #b7b7b7;
      }
      .text {
        color: #b7b7b7;
      }
    }
  }
}

.ivu-input {
  border-radius: 0px;
}

.ivu-input-large {
  height: 45px;
}

.ivu-input-wrapper-large .ivu-input-prefix i,
.ivu-input-wrapper-large .ivu-input-suffix i {
  line-height: 45px;
}

.ivu-input-wrapper-large .ivu-input-icon {
  line-height: 45px;
}

.ivu-btn-info[disabled],
.ivu-btn-info[disabled]:hover {
  // color: #a37474 !important;
}

</style>
